package StudyCode.summary.csv;

import java.util.ArrayList;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class ArrayListToCSVLine {
	public static void main(String[] args) {
		ArrayList<String> strings = new ArrayList<>();
		strings.add("www");
		strings.add("tah1986");
		strings.add("com");
		System.out.println("String 集合:");
		for (String so : strings) {
			System.out.println(so);
		}
		System.out.println("集合转为CSV行");
		System.out.println(toCSVLine(strings));
	}

	public static String toCSVLine(ArrayList<?> strArrList) {
		if (strArrList == null) {
			return "";
		}
		String[] strArray = new String[strArrList.size()];
		for (int idx = 0; idx < strArrList.size(); idx++) {
			strArray[idx] = (String) strArrList.get(idx);
		}
		return toCSVLine(strArray);
	}

	public static String toCSVLine(String[] strArray) {
		if (strArray == null) {
			return "";
		}
		StringBuffer cvsLine = new StringBuffer();
		for (int idx = 0; idx < strArray.length; idx++) {
			String item = addQuote(strArray[idx]);
			cvsLine.append(item);
			if (strArray.length - 1 != idx) {
				cvsLine.append(',');
			}
		}
		return cvsLine.toString();
	}


	private static String addQuote(String item) {
		if (item == null || item.length() == 0) {
			return "\"\"";
		}
		StringBuffer sb = new StringBuffer();
		sb.append('"');
		for (int idx = 0; idx < item.length(); idx++) {
			char ch = item.charAt(idx);
			if ('"' == ch) {
				sb.append("\"\"");
			} else {
				sb.append(ch);
			}
		}
		sb.append('"');
		return sb.toString();
	}
}

